import React, { useEffect, useState } from 'react';
import { Table } from 'antd';
import { Breadcrumb ,Button } from 'antd';
import axios from 'axios';
import { useNavigate } from 'react-router-dom'
const Timetable = () => {
    const [data, setData] = useState([]);
    const [coursedata, setcourseData] = useState([]);
    const navigate = useNavigate()
    const daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

    useEffect(() => {
        const studentid = localStorage.getItem('studentid');
    axios.post('http://localhost:8000/gettakecourselist', { studentid: studentid })
      .then(response => {
        console.log(response.data);
        setcourseData(response.data);
        const timetableData = [
            { time: '8:00-9:30', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '10:00-11:30', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '14:00-15:30', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '16:00-17:30', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '18:30-20:00', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            { time: '20:30-22:00', Monday: '', Tuesday: '', Wednesday: '', Thursday: '', Friday: '', Saturday: '', Sunday: '' },
            // Other course schedules for different time periods
        ];
        // 遍历每个课程，更新课程表数据
      response.data.forEach(course => {
        const { time,coursename } = course;
        //console.log(time,coursename);
        // 找到timetableData中对应时间槽和星期几的索引
        if (time) {
            const parts = time.split(", ");
            for (let part of parts) {
                console.log(coursename+part);
                const matches = part.match(/^([a-zA-Z]+)(\d+:\d+-\d+:\d+)$/);
                if (matches) {
                const day = matches[1];
                const timeRange = matches[2];
                console.log(day); 
                console.log(timeRange);
                    const index = timetableData.findIndex(slot => slot.time === timeRange);
                    
                    if (index !== -1) {
                        // 更新相应时间和日期槽中的课程名
                        timetableData[index][day] += ` ${coursename}`
                    }
            }
            }
        }
      });

      // 将更新后的timetableData设置为状态
      setData(timetableData);
    })
    .catch(error => {
      console.error('错误:', error);
    });
}, []);

const handleCellClick = (value) => {
    console.log('点击了：', value);
  
    // 在这里执行点击事件后的逻辑
    const foundCourse = coursedata.find(course => course.coursename === value);
  
    if (foundCourse) {
      const id = foundCourse.courseid;
      console.log('找到匹配的 courseid:', id);
      navigate(`/Layoutstudent/coursetimetable/${id}`);
  
      // 在这里执行处理找到 courseid 的逻辑
    } else {
      console.log('未找到匹配的课程');
      // 在这里执行未找到匹配课程的逻辑
    }
  };

  const exportToCSV = () => {
    const csvRows = [];
  
    // 添加表头行
    const header = ['时间', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
    csvRows.push(header.join(',')); // 将表头行以逗号连接并添加到CSV行数组中
  
    // 添加数据行
    data.forEach(row => {
      const values = [
        row.time,
        row.Monday,
        row.Tuesday,
        row.Wednesday,
        row.Thursday,
        row.Friday,
        row.Saturday,
        row.Sunday
      ];
      csvRows.push(values.join(',')); // 将每行数据以逗号连接并添加到CSV行数组中
    });
  
    // 使用CSV数据创建一个Blob对象
    const csvData = csvRows.join('\n'); // 将CSV行数组以换行符连接成字符串
    const blob = new Blob([csvData], { type: 'text/csv' }); // 创建Blob对象
  
    // 创建一个链接元素以下载CSV文件
    const url = URL.createObjectURL(blob); // 创建一个URL对象
    const a = document.createElement('a'); // 创建一个<a>元素
    a.href = url; // 设置链接地址为CSV文件的URL
    a.download = 'timetable.csv'; // 设置下载文件的名称为timetable.csv
  
    // 将链接添加到页面并触发下载
    document.body.appendChild(a); // 将<a>元素添加到页面
    a.click(); // 触发下载
  
    // 清理：移除链接元素
    document.body.removeChild(a); // 从页面中移除<a>元素
};


    const columns = [
        {
            title: '时间',
            dataIndex: 'time',
            fixed: 'left',
            width: 150,
            ellipsis: true,
        },
        {
            title: '星期一',
            dataIndex: 'Monday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
          },
        {
            title: '星期二',
            dataIndex: 'Tuesday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
        {
            title: '星期三',
            dataIndex: 'Wednesday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
        {
            title: '星期四',
            dataIndex: 'Thursday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
        {
            title: '星期五',
            dataIndex: 'Friday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
        {
            title: '星期六',
            dataIndex: 'Saturday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
        {
            title: '星期天',
            dataIndex: 'Sunday',
            width: 150,
            ellipsis: true,
            render: (text) => {
              const courses = text.split(' ').filter(course => course.trim() !== '');
              return courses.map((course, index) => (
                <div key={index}>
                  <a onClick={() => handleCellClick(course)}>{course}</a>
                </div>
              ));
            },
        },
    ];

    return (
        <div>
      <Breadcrumb>
        <Breadcrumb.Item>Timetable</Breadcrumb.Item>
      </Breadcrumb>
            <h1>课程表</h1>
            <Button
                type="primary"
                style={{ position: 'absolute', top: 150, right: 100 }}
                onClick={exportToCSV}
            >
                导出
            </Button>
            <Table
                rowKey={(record, index) => index}
                columns={columns}
                dataSource={data}
                scroll={{}} // 设置为空对象，禁用水平滚动
                pagination={false}
            />
        </div>
    );
};

export default Timetable;

